package example

import (
	"fmt"
	"sync"
)

var times = 100

// 三个函数，分别打印"cat"、"dog"、"fish"
func cat(catChan, dogChan chan bool) {
	defer wg.Done()      //  函数完成将协组减1
	defer close(dogChan) // 释放channel资源
	for i := 0; i < times; i++ {
		<-catChan // 阻塞获取资源
		fmt.Printf("times:%v\n", i+1)
		fmt.Println("cat ...")
		dogChan <- true //  谁声明，谁关闭
	}
}

func dog(dogChan, fishChan chan bool) {
	defer wg.Done()
	defer close(fishChan)
	for i := 0; i < times; i++ {
		<-dogChan
		fmt.Println("dog ...")
		fishChan <- true
	}
}

func fish(fishChan, catChan chan bool) {
	defer wg.Done()
	defer close(catChan)
	for i := 0; i < times; i++ {
		<-fishChan
		fmt.Println("fish ...")
		catChan <- true
	}
}

// 要求每个函数都启一个Goroutine，请按照"cat"、"dog"、"fish"顺序打印在屏幕上，100次
var wg sync.WaitGroup

func printOrderByGoroutine() {
	catChan := make(chan bool, 2)
	dogChan := make(chan bool, 2)
	fishChan := make(chan bool, 2)

	go cat(catChan, dogChan)
	go dog(dogChan, fishChan)
	go fish(fishChan, catChan)

	catChan <- true
	wg.Add(3) // 添加3个协程计数
	wg.Wait() // 等待协程执行结束
}
